package cn.wit.front.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AesUtils {
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    private static final String AES = "AES";
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final int AES_KEY_SIZE = 256;
    private static final int AES_BLOCK_SIZE = 128;
    private static final String INITIAL_VECTOR = "0123456789abcdef";

    /**
     * 加密
     *
     * @param plaintext 明文
     * @param key       密钥
     * @return 密文
     * @throws Exception 异常
     */
    public static String encrypt(String plaintext, String key) throws Exception {
        byte[] keyBytes = key.getBytes(UTF8);
        byte[] ivBytes = INITIAL_VECTOR.getBytes(UTF8);

        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, AES);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

        byte[] encrypted = cipher.doFinal(plaintext.getBytes(UTF8));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    /**
     * 解密
     *
     * @param ciphertext 密文
     * @param key        密钥
     * @return 明文
     * @throws Exception 异常
     */
    public static String decrypt(String ciphertext, String key) throws Exception {
        byte[] keyBytes = key.getBytes(UTF8);
        byte[] ivBytes = INITIAL_VECTOR.getBytes(UTF8);

        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, AES);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

        byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
        return new String(decrypted, UTF8);
    }
}
